package com.irdstudio.apicenter.console.controller.make;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.irdstudio.apicenter.console.startup.MacmsRoot;

@Controller
@RequestMapping(value = "/appProject")
public class AppProjectExploreAction {

	/**
	 * 应用工程管理
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "projectExplore")
	public ModelAndView projectExplore(HttpServletRequest request)
			throws Exception {

		// 取得传入应用标识
		String appId = request.getParameter("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// String
		// jsonStr=GetAppTree.getAppTree("e:/Project/2015_MOBILE_APPS/zqjr/www");
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("appid", appId);
		modelAndView.setViewName("make/projectExplore");
		return modelAndView;
	}

	@RequestMapping(value = "projectFileList")
	public @ResponseBody
	ModelAndView projectFileList(HttpServletRequest request) throws Exception {

		// 取得传入应用标识
		String appId = request.getParameter("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// 判断工程目录是否存在,如果不存在,则从SVN下更新代码
		String filepath = MacmsRoot.getMacmsPathService()
				.getMacmsWorkspacePath().concat("/appprj/").concat(appId)
				.concat("/");

		File file = new File(filepath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
			// 首次，则从SVN上checkout工程下来
			MacmsRoot.getSvnProjectService().checkoutProject(appId);
		} else {
			// 后续则从SVN上更新工程
			MacmsRoot.getSvnProjectService().updateProject(appId);
		}

		// String
		// jsonStr=GetAppTree.getAppTree("e:/Project/2015_MOBILE_APPS/zqjr/www");
		String jsonStr = GetAppTree.getAppTree(filepath);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("jsonStr", jsonStr);
		Thread.sleep(5 * 1000);
		return modelAndView;
	}

	@RequestMapping(value = "openfile", method = RequestMethod.POST)
	public void openFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String filePath = request.getParameter("file");
		StringBuffer content = new StringBuffer("");
		if (!StringUtils.isEmpty(filePath)) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(filePath), "UTF-8"));
			String data = br.readLine();// 一次读入一行，直到读入null为文件结束
			while (data != null) {
				content.append(data + "\n");
				data = br.readLine(); // 接着读下一行
			}
			br.close();
		}
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("content", content.toString());
		String jsonResult = JSON.toJSONString(map);
		renderData(response, jsonResult);
	}

	@RequestMapping(value = "savefile", method = RequestMethod.POST)
	public void saveFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String filePath = request.getParameter("path");
		String content = request.getParameter("content");
		String flag = "success";
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				flag = "failed";
			} else {
				BufferedWriter bWriter = new BufferedWriter(
						new OutputStreamWriter(new FileOutputStream(file),
								"UTF-8"));
				bWriter.write(content);
				bWriter.close();
			}
		} catch (Exception e) {
			flag = "failed";
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		renderData(response, jsonResult);
	}

	/**
	 * 通过PrintWriter将响应数据写入response，ajax可以接受到这个数据
	 * 
	 * @param response
	 * @param data
	 */
	private void renderData(HttpServletResponse response, String data) {
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(data);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}
	}
}
